package git.soulbgm.handler;

import git.soulbgm.common.TcpConnectMap;
import git.soulbgm.pojo.BaseMsg;
import git.soulbgm.utils.ByteUtil;
import git.soulbgm.utils.IpUtil;
import git.soulbgm.utils.Sequence;
import git.soulbgm.utils.SerializeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-10-17 13:39
 * @description
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class TcpSimpleHandle extends SimpleChannelInboundHandler<ByteBuf> {

    private Sequence sequence = new Sequence(1, 1);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals(event.state())) {
                // 长期未收到客户端推送的消息
                // 可以选择重新连接
            } else if (IdleState.WRITER_IDLE.equals(event.state())) {
                // 长期未向客户端推送消息
                // 发送心跳包
//                ctx.channel().writeAndFlush(ByteUtil.stringToByteBuf("111222333$_$"));
            } else if (IdleState.ALL_IDLE.equals(event.state())) {
                // 长期未收到客户端推送的消息并且也长期未向客户端推送消息
            }
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String host = IpUtil.getTcpHost(ctx);
        TcpConnectMap.put(sequence.nextId(), (NioSocketChannel) ctx.channel());
        log.info("{}地址用户连接", host);
    }

    /**
     * 当客户端连接断开时调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String host = IpUtil.getTcpHost(ctx);
        TcpConnectMap.remove((NioSocketChannel) ctx.channel());
        log.warn("{}地址用户离线", host);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] bytes = ByteUtil.byteBufToByteArray(msg);
        BaseMsg baseMsg = SerializeUtil.deserializer(bytes, BaseMsg.class);
        log.info("消息:{}", baseMsg.toString());
        ctx.channel().writeAndFlush(ByteUtil.stringToByteBuf("已收到消息$_$"));
    }
}
